package com.skywork.dao;

import java.io.StringReader;
import java.util.Map;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.ibatis.annotations.Param;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class CommonDataProvider {

	public String queryDynamicSQL(@Param("hql") String hql, @Param("param") Map<String, ?> param) {
		// SQL sql = new SQL().SELECT("*").FROM(hql);
		// if (StringUtils.isNotBlank(reqeust.getName())) {
		// sql.WHERE("full_name LIKE #{name}");
		// }
		// if (StringUtils.isNotBlank(reqeust.getMobile())) {
		// sql.WHERE("mobile = #{mobile}");
		// }

		StringReader sr = new StringReader(hql);
		InputSource source = new InputSource(sr);

		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();

		try {
			Node node = (Node) xpath.evaluate("script", source, XPathConstants.NODE);
			if (node != null) {
				hql = node.getTextContent();
				NodeList whenNodeList = (NodeList) xpath.evaluate("when", node, XPathConstants.NODESET);
				for (int i = 0; i < whenNodeList.getLength(); i++) {
					Node whenNode = whenNodeList.item(i);
					String test = whenNode.getAttributes().getNamedItem("test").getNodeValue().replaceAll(" ", "");
					if (test.lastIndexOf("!=null") >= -1) {
						String key = test.substring(0, test.lastIndexOf("!=null")).replace("param.", "");
						if (param == null || !param.containsKey(key)) {
							hql = hql.replace(whenNode.getTextContent(), "");
						}
					}

				}
			}

		} catch (XPathExpressionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return hql;
	}
}
